<template>
  <div class="coupon-container">
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keyword"
            placeholder="优惠券名称/描述"
            clearable
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            style="width: 150px"
            clearable
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span class="title">优惠券列表</span>
          <div class="button-group">
            <el-button type="primary" @click="handleAdd">新增优惠券</el-button>
            <el-button type="success" @click="handleBatchAdd"
              >批量添加</el-button
            >
            <el-button
              type="danger"
              :disabled="!selectedRows.length"
              @click="handleBatchDelete"
              >批量删除</el-button
            >
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="id" width="80" align="center" />
        <el-table-column prop="name" label="优惠券名称" min-width="150" />
        <el-table-column prop="type" label="类型" width="120" align="center">
          <template #default="{ row }">
            <el-tag
              :type="
                row.type === '0'
                  ? 'success'
                  : row.type === '1'
                    ? 'warning'
                    : row.type === '2'
                      ? 'primary'
                      : 'danger'
              "
            >
              {{
                row.type === "0"
                  ? "无门槛"
                  : row.type === "1"
                    ? "类型优惠"
                    : row.type === "2"
                      ? "满减优惠"
                      : "新人优惠"
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="value" label="优惠值" width="100" align="center">
          <template #default="{ row }">
            {{ row.type === 2 ? `${row.value}折` : `￥${row.value}` }}
          </template>
        </el-table-column>
        <el-table-column
          prop="minAmount"
          label="最低使用金额"
          width="120"
          align="center"
        >
          <template #default="{ row }">
            {{ row.minAmount === 0 ? "无门槛" : `￥${row.minAmount}` }}
          </template>
        </el-table-column>
        <el-table-column
          prop="timeEffect"
          label="有效期(天)"
          width="100"
          align="center"
        />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag
              :type="
                row.status === 0
                  ? 'success'
                  : row.status === 1
                    ? 'warning'
                    : row.status === 2
                      ? 'info'
                      : 'danger'
              "
            >
              {{
                row.status === 0
                  ? "未兑换"
                  : row.status === 1
                    ? "已兑换"
                    : row.status === 2
                      ? "已使用"
                      : "已过期"
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="createdTime"
          label="创建时间"
          width="180"
          align="center"
        >
          <template #default="{ row }">
            {{ formatDateTime(row.createdTime) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="updatedTime"
          label="更新时间"
          width="180"
          align="center"
        >
          <template #default="{ row }">
            {{ row.updatedTime ? formatDateTime(row.updatedTime) : "-" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="updatedBy"
          label="操作人"
          width="120"
          align="center"
        >
          <template #default="{ row }">
            {{ row.updatedBy || "-" }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" align="center">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              :disabled="row.status !== 0"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              link
              type="danger"
              :disabled="row.status === 2"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
            <el-button link type="success" @click="handleViewCode(row)">
              查看卡密
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[5, 10, 20, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑优惠券弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增优惠券' : '编辑优惠券'"
      width="500px"
      @close="resetForm(formRef)"
    >
      <el-form
        ref="formRef"
        :model="couponForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="优惠券名称" prop="name">
          <el-input v-model="couponForm.name" placeholder="请输入优惠券名称" />
        </el-form-item>
        <el-form-item label="优惠类型" prop="type">
          <el-select v-model="couponForm.type" placeholder="请选择优惠类型">
            <el-option label="无门槛" value="0" />
            <el-option label="类型优惠" value="1" />
            <el-option label="满减优惠" value="2" />
            <el-option label="新人优惠" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="优惠金额" prop="value">
          <el-input-number
            v-model="couponForm.value"
            :min="0"
            :precision="2"
            :step="10"
          />
          <span class="unit">元</span>
        </el-form-item>
        <el-form-item label="最低金额" prop="minAmount">
          <el-input-number
            v-model="couponForm.minAmount"
            :min="0"
            :precision="2"
            :step="10"
          />
          <span class="unit">元</span>
        </el-form-item>
        <el-form-item label="有效期" prop="timeEffect">
          <el-input-number
            v-model="couponForm.timeEffect"
            :min="1"
            :precision="0"
            :step="1"
          />
          <span class="unit">天</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm(formRef)"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 批量添加优惠券弹窗 -->
    <el-dialog
      v-model="batchDialogVisible"
      title="批量添加优惠券"
      width="500px"
      @close="resetForm(batchFormRef)"
    >
      <el-form
        ref="batchFormRef"
        :model="batchCouponForm"
        :rules="batchRules"
        label-width="100px"
      >
        <el-form-item label="优惠券名称" prop="name">
          <el-input
            v-model="batchCouponForm.name"
            placeholder="请输入优惠券名称"
          />
        </el-form-item>
        <el-form-item label="优惠类型" prop="type">
          <el-select
            v-model="batchCouponForm.type"
            placeholder="请选择优惠类型"
          >
            <el-option label="无门槛" value="0" />
            <el-option label="类型优惠" value="1" />
            <el-option label="满减优惠" value="2" />
            <el-option label="新人优惠" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="优惠金额" prop="value">
          <el-input-number
            v-model="batchCouponForm.value"
            :min="0"
            :precision="2"
            :step="10"
          />
          <span class="unit">元</span>
        </el-form-item>
        <el-form-item label="最低金额" prop="minAmount">
          <el-input-number
            v-model="batchCouponForm.minAmount"
            :min="0"
            :precision="2"
            :step="10"
          />
          <span class="unit">元</span>
        </el-form-item>
        <el-form-item label="有效期" prop="timeEffect">
          <el-input-number
            v-model="batchCouponForm.timeEffect"
            :min="1"
            :precision="0"
            :step="1"
          />
          <span class="unit">天</span>
        </el-form-item>
        <el-form-item label="生成数量" prop="quantity">
          <el-input-number
            v-model="batchCouponForm.quantity"
            :min="1"
            :max="100"
            :step="1"
          />
          <span class="unit">张</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitBatchForm(batchFormRef)"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getAllCoupons,
  addCoupons,
  deleteCoupons,
  deleteCoupon,
  updateCoupon
} from "@/api/coupon";
import { formatDateTime } from "@/utils/tools";
import { log } from "node:util";

onMounted(() => {
  getAllCouponsAll();
});

// 定义数据接口
interface CouponItem {
  id: string;
  code: string;
  name: string;
  type: string;
  value: number;
  minAmount: number;
  timeEffect: number;
  status: number;
  createdTime: string;
  createdBy: string | null;
  updatedBy: string | null;
  updatedTime: string | null;
  isDeleted: number;
}

interface ApiResponse<T> {
  code: number;
  message: string;
  data: T;
}

interface PageResult<T> {
  pageNo: number;
  pageSize: number;
  result: T[];
  total: number;
  totalPages: number;
  start: number;
  end: number;
}

const getAllCouponsAll = async () => {
  // 重置搜索条件
  searchForm.keyword = "";
  searchForm.status = "";
  searchForm.dateRange = [];
  // 使用 handleSearch 进行查询
  handleSearch();
};

const pageNo = ref(1);
const pageSize = ref(10);
const total = ref(0);

const searchForm = reactive({
  keyword: "",
  status: "",
  dateRange: []
});

// 定义表单数据和类型
interface CouponForm {
  id: string;
  code: string;
  name: string;
  type: string;
  value: number;
  minAmount: number;
  timeEffect: number;
}

// 表单数据
const couponForm = reactive<CouponForm>({
  id: "",
  code: "",
  name: "",
  type: "0",
  value: 0,
  minAmount: 0,
  timeEffect: 1
});

const rules = reactive<FormRules>({
  name: [{ required: true, message: "请输入优惠券名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择优惠券类型", trigger: "change" }],
  value: [{ required: true, message: "请输入优惠金额", trigger: "blur" }],
  minAmount: [
    { required: true, message: "请输入最低使用金额", trigger: "blur" }
  ],
  timeEffect: [
    { required: true, message: "请输入有效期天数", trigger: "blur" },
    { type: "number", min: 1, message: "有效期至少1天", trigger: "blur" }
  ]
});

const dialogVisible = ref(false);
const dialogType = ref<"add" | "edit">("add");
const formRef = ref<FormInstance>();
const loading = ref(false);

const statusOptions = [
  { label: "全部状态", value: "" },
  { label: "未兑换", value: 0 },
  { label: "已兑换", value: 1 },
  { label: "已使用", value: 2 },
  { label: "已过期", value: 3 }
];

const couponTypes = [
  { label: "无门槛", value: "0" },
  { label: "类型优惠", value: "1" },
  { label: "满减优惠", value: "2" },
  { label: "新人优惠", value: "3" }
];

const tableData = ref<CouponItem[]>([]);

const handleSearch = async () => {
  loading.value = true;
  try {
    // 处理日期范围
    const [startTime, endTime] = searchForm.dateRange || [];

    // 构建查询参数
    const searchParams = {
      keyword: searchForm.keyword,
      status: searchForm.status === "" ? undefined : Number(searchForm.status),
      startTime: startTime ? formatDate(startTime) : undefined,
      endTime: endTime
        ? formatDate(new Date(endTime.getTime() + 24 * 60 * 60 * 1000 - 1))
        : undefined
    };

    const res = await getAllCoupons(pageNo.value, pageSize.value, searchParams);

    if (res.code === 200) {
      tableData.value = res.data.result;
      total.value = res.data.total;
      pageNo.value = res.data.pageNo;
      pageSize.value = res.data.pageSize;
    } else {
      ElMessage.error(res.message || "搜索失败");
    }
  } catch (error) {
    ElMessage.error("搜索失败");
  } finally {
    loading.value = false;
  }
};

// 格式化日期为 yyyy-MM-dd HH:mm:ss
const formatDate = (date: Date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

const handleReset = () => {
  searchForm.keyword = "";
  searchForm.status = "";
  searchForm.dateRange = [];
  // 重置后自动搜索
  pageNo.value = 1;
  handleSearch();
};

const handleAdd = () => {
  dialogType.value = "add";
  Object.assign(couponForm, {
    id: "",
    code: "",
    name: "",
    type: "0",
    value: "10",
    minAmount: "10.01",
    timeEffect: 1
  });
  dialogVisible.value = true;
};

const handleEdit = (row: CouponItem) => {
  dialogType.value = "edit";
  Object.assign(couponForm, {
    id: row.id,
    code: row.code,
    name: row.name,
    type: row.type,
    value: row.value,
    minAmount: row.minAmount,
    timeEffect: row.timeEffect
  });
  dialogVisible.value = true;
};

const handleDelete = (row: CouponItem) => {
  if (row.status === 2) {
    ElMessage.warning("已使用的优惠券不能删除");
    return;
  }

  ElMessageBox.confirm("确定要删除该优惠券吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    try {
      const res = await deleteCoupon(Number(row.id));
      if (res.code === 200) {
        ElMessage.success("删除成功");
        handleSearch(); // 刷新列表
      } else {
        ElMessage.error(res.message || "删除失败");
      }
    } catch (error) {
      ElMessage.error("删除失败");
    }
  });
};

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;

  await formEl.validate(async valid => {
    if (valid) {
      try {
        const { timeEffect, ...rest } = couponForm;
        const formData = {
          ...rest,
          time_effect: timeEffect,
          status: 0
        };

        let res;
        if (dialogType.value === "edit") {
          // 编辑模式
          res = await updateCoupon(Number(formData.id), formData);
        } else {
          // 新增模式
          res = await addCoupons(formData, 1);
        }

        if (res.code === 200) {
          ElMessage.success(
            dialogType.value === "edit" ? "修改优惠券成功" : "新增优惠券成功"
          );
          dialogVisible.value = false;
          handleSearch(); // 刷新列表
        } else {
          ElMessage.error(
            res.message ||
              (dialogType.value === "edit"
                ? "修改优惠券失败"
                : "新增优惠券失败")
          );
        }
      } catch (error) {
        ElMessage.error("操作失败");
      }
    }
  });
};

const handleSizeChange = (val: number) => {
  pageSize.value = val;
  pageNo.value = 1;
  handleSearch(); // 改用 handleSearch 以保持搜索条件
};

const handleCurrentChange = (val: number) => {
  pageNo.value = val;
  handleSearch(); // 改用 handleSearch 以保持搜索条件
};

const formatDateTime = (dateStr: string) => {
  const date = new Date(dateStr);
  return date.toLocaleString();
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  dialogType.value = "add";
};

const handleViewCode = (row: CouponItem) => {
  ElMessageBox.alert(row.code, "优惠券卡密", {
    confirmButtonText: "复制",
    callback: action => {
      if (action === "confirm") {
        navigator.clipboard
          .writeText(row.code)
          .then(() => {
            ElMessage({
              type: "success",
              message: "卡密已复制到剪贴板"
            });
          })
          .catch(() => {
            ElMessage({
              type: "error",
              message: "复制失败，请手动复制"
            });
          });
      }
    }
  });
};

// 批量添加相关数据
interface BatchCouponForm extends CouponForm {
  quantity: number;
  status: number;
}

const batchDialogVisible = ref(false);
const batchFormRef = ref<FormInstance>();

const batchCouponForm = reactive<BatchCouponForm>({
  id: "",
  code: "",
  name: "",
  type: "0",
  value: 0,
  minAmount: 0,
  timeEffect: 1,
  status: 0,
  quantity: 1
});

const batchRules = reactive<FormRules>({
  ...rules,
  quantity: [
    { required: true, message: "请输入生成数量", trigger: "blur" },
    {
      type: "number",
      min: 1,
      max: 100,
      message: "数量范围1-100",
      trigger: "blur"
    }
  ]
});

const handleBatchAdd = () => {
  batchDialogVisible.value = true;
  Object.assign(batchCouponForm, {
    id: "",
    name: "",
    type: "1",
    value: 0,
    minAmount: 0,
    quantity: 1,
    timeEffect: 1
  });
};

const submitBatchForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;

  await formEl.validate(async valid => {
    if (valid) {
      try {
        const { timeEffect, quantity, ...rest } = batchCouponForm;
        const formData = {
          ...rest,
          time_effect: timeEffect,
          status: 0
        };
        const response = await addCoupons(formData, quantity);
        const res = response.data as ApiResponse<any>;
        if (res.code === 200) {
          ElMessage.success("批量添加优惠券成功");
          batchDialogVisible.value = false;
          getAllCouponsAll(); // 刷新列表
        } else {
          ElMessage.error(res.message || "批量添加优惠券失败");
        }
      } catch (error) {
        ElMessage.error("操作失败");
      }
    }
  });
};

// 选中的行
const selectedRows = ref<CouponItem[]>([]);

// 表格多选
const handleSelectionChange = (rows: CouponItem[]) => {
  selectedRows.value = rows;
};

// 批量删除
const handleBatchDelete = () => {
  if (!selectedRows.value.length) {
    ElMessage.warning("请选择要删除的优惠券");
    return;
  }

  // 检查是否有不能删除的优惠券
  const hasInvalidStatus = selectedRows.value.some(row => row.status === 2);
  if (hasInvalidStatus) {
    ElMessage.warning("已使用的优惠券不能删除");
    return;
  }

  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRows.value.length} 张优惠券吗？`,
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }
  ).then(async () => {
    try {
      const ids = selectedRows.value.map(row => Number(row.id));
      const res = await deleteCoupons(ids);
      if (res.code === 200) {
        ElMessage.success("删除成功");
        handleSearch(); // 刷新列表
      } else {
        ElMessage.error(res.message || "删除失败");
      }
    } catch (error) {
      ElMessage.error("删除失败");
    }
  });
};

defineOptions({
  name: "Coupon"
});
</script>

<style scoped lang="scss">
.coupon-container {
  padding: 20px;
  background: #f5f7fa;

  .search-card {
    margin-bottom: 20px;
  }

  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .title {
        font-size: 16px;
        font-weight: bold;
        color: #303133;
      }
    }
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  :deep(.el-form-item) {
    margin-bottom: 18px;

    .unit {
      margin-left: 8px;
      color: #606266;
    }
  }

  :deep(.el-tag) {
    min-width: 60px;
  }

  .button-group {
    display: flex;
    gap: 10px;
  }
}
</style>
